package com.wzd.learn.springboot;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;

@Configuration
public class WebConfig extends WebMvcConfigurationSupport {
	/**
	 * 异常处理器
	 */
	@Override
	public void extendHandlerExceptionResolvers(
			List<HandlerExceptionResolver> exceptionResolvers) {
		DefaultHandlerExceptionResolver resolverHandler = new DefaultHandlerExceptionResolver();
		exceptionResolvers.add(0, resolverHandler);
	}

	@Override
	protected void addFormatters(FormatterRegistry registry) {
		registry.addConverter(dateFormateConvert());
	}

	/**
	 * 全局时间参数类型转换器
	 */
	@Bean
	public Converter<String, Date> dateFormateConvert() {
		final String dateFormat = "yyyy-MM-dd HH:mm:ss";
		final String shortDateFormat = "yyyy-MM-dd";
		return new Converter<String, Date>() {
			@Override
			public Date convert(String source) {
				if (StringUtils.isEmpty(source)) {
					return null;
				}
				source = source.trim();
				try {
					if (source.contains("-")) {
						SimpleDateFormat formatter;
						if (source.contains(":")) {
							formatter = new SimpleDateFormat(dateFormat);
						} else {
							formatter = new SimpleDateFormat(shortDateFormat);
						}

						Date dtDate = formatter.parse(source);
						return dtDate;
					} else if (source.matches("^\\d+$")) {
						Long lDate = new Long(source);
						return new Date(lDate);
					}
				} catch (Exception e) {
					throw new RuntimeException(String.format(
							"parser %s to Date fail", source));
				}
				throw new RuntimeException(String.format(
						"parser %s to Date fail", source));
			}
		};
	}

	/*
	 * Fastjson replace Jackson
	 */
	@Override
	public void configureMessageConverters(
			List<HttpMessageConverter<?>> converters) {

		// 定义一个转换消息的对象
		FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();

		// 添加fastjson的配置信息 比如 ：是否要格式化返回的json数据
		FastJsonConfig fastJsonConfig = new FastJsonConfig();
		fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
		// 在转换器中添加配置信息
		fastConverter.setFastJsonConfig(fastJsonConfig);

		// 将转换器添加到converters中
		converters.add(fastConverter);
	}

}
